package week05.q10;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;

/**
 * @author lv
 * @date 2021/4/17 23:41
 */
public class ConnectionPool {
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=utf-8&serverTimezone=GMT";
    private static final String USER = "root";
    private static final String PASSWORD = "123456";
    public static LinkedList<Connection> pool;
    private static Connection getOneConnection(){
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(URL,USER,PASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return  conn;
    }
    public static Connection getConnection(){
        if (pool == null){
            pool = new LinkedList<>();
            for (int i = 0; i < 2;i++){
                pool.add(getConnection());
            }
        }
        if (pool.size() <= 0){
            pool.add(getOneConnection());
        }
        return  pool.remove();
    }
    public static void close(Connection conn){
        pool.add(conn);
    }
}
